<template>
  <el-container>
    <el-main>
      <div class="sa-flex" v-if="form.model?.status?.value==3">
        <div class="sa-width-100 left-t">拒绝理由：</div>
        <div>{{ form.model.remark }}</div>
        <!-- <el-button
            class="sa-m-l-12"
            type="primary"
            @click="">充值
        </el-button> -->
      </div>
      <el-form :model="form.model" :rules="form.rules" ref="formRef" label-width="100px">
        
       
            <div class="title">基础信息</div>
            <el-form-item required label="任务名称" prop="title">
              <el-input v-model="form.model.title" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item required label="任务封面图" prop="title_cover_image">
              <sa-uploader v-model="form.model.title_cover_image" :multiple="false" :fileType="['image']"></sa-uploader>
            </el-form-item>
            <el-form-item style="width:460px" required label="活动时间" prop="actTimerange" class="get-time">
              <el-date-picker
                v-model="form.model.actTimerange"
                type="datetimerange"
                value-format="YYYY-MM-DD"
                format="YYYY-MM-DD"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                prefix-icon="Calendar"
              ></el-date-picker>
            </el-form-item>
            <el-form-item required label="上架时间" prop="start_time">
                <el-date-picker
                  v-model="form.model.start_time"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择"
                  prefix-icon="Calendar"
                  :editable="false"
                />
            </el-form-item>
          
            <div class="title">报名条件</div>
            <el-form-item required label="平台要求" prop="platform_require">
              <el-checkbox-group v-model="form.model.platform_require">
                <el-checkbox label="抖音" value="douying" />
                <el-checkbox label="快手" value=" kuaishou" />
              </el-checkbox-group>
            </el-form-item>
            <el-form-item required label="作品形式" prop="work_form">
              <el-checkbox-group v-model="form.model.work_form">
                <el-checkbox label="视频" value="video" />
                <el-checkbox label="直播" value="live" />
              </el-checkbox-group>
            </el-form-item>
            <el-form-item required label="地域要求" prop="province_limit">
              <el-input v-model="form.model.province_limit" placeholder="请输入“全国”或“某某市”，例如：杭州市"></el-input>
            </el-form-item>
              <el-form-item required label="接单等级" prop="levelList">
                 <el-button type="primary" @click="addLevel">添加等级要求</el-button>
                 <template v-for="(item,index) in state.levelList" :key="index">
                  <div class="sa-flex" style="width: 100%;">
                    <el-input disabled class="sa-m-t-10" v-model="state.levelList[index].txt" placeholder="请输入"></el-input>
                    <el-button size="small" class="sa-m-t-10 sa-m-l-10" type="primary" @click="changeLevel(index)">编辑</el-button>
                    <el-button size="small" class="sa-m-t-10 sa-m-l-10" type="danger" @click="delLevel(index)">删除</el-button>
                  </div>
                 </template>
              </el-form-item>
              <el-form-item label="其它要求">
              <el-input v-model="form.model.other_require" placeholder="请输入" type="textarea"></el-input>
            </el-form-item>
          

       
            <div class="title">店铺信息</div>
           
            <el-form-item required label="店铺名称" prop="storeName">
              <el-select
                  @click.stop="openStoreList()"
                  v-model="state.store.id"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in [state.store]"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="联系人">
              <el-input v-model="form.model.link" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="联系电话">
              <el-input v-model="form.model.mobile" placeholder="请输入"></el-input>
            </el-form-item>
              <el-form-item label="抖音门店POI">
                <el-input v-model="form.model.poiId" placeholder="请输入 例如：123456789"></el-input>
              </el-form-item>
              <el-form-item label="商家优势">
                <el-input v-model="form.model.selling_point" placeholder="请输入 例如：味道经典、食材新鲜、卫生干净"></el-input>
              </el-form-item>
              <el-form-item label="详细地址">
                <el-input v-model="form.model.shop_address" placeholder="请输入“全国”或“某某市”，例如：杭州市"></el-input>
              </el-form-item>
      </el-form>
      
    </el-main>
    <el-footer class="sa-footer--submit">
      <el-button v-if="props.modal.params.type=='add'" type="primary" @click="confirm"
        >保存</el-button>
      <el-button v-if="props.modal.params.type=='again'" type="primary" @click="confirm"
      >重新提交</el-button>
    </el-footer>
  </el-container>
</template>
<script setup>
  import { onMounted, reactive, ref, unref } from 'vue';
  import { api } from '../task.service';
  import { cloneDeep } from 'lodash';
  import {useModal, usePagination} from '@/sheep/hooks';
  import storeList from '../comment/storeList.vue';
  import editLevel from './editLevel.vue';

  import GoodsSelect from '@/app/shop/admin/goods/goods/select.vue';


  const emit = defineEmits(['modalCallBack']);
  const props = defineProps({
    modal: {
      type: Object,
    },
  });
  const state = reactive({
    store:{},
    videoList:[],
    good:{},
    groupList:[],//素材列表
    levelList:[],//接单等级要求
  });
  // 校验是否选择了接单等级
  const levelListPass = (rule, value, callback) => {
    if (state.levelList.length === 0) {
      callback(new Error('请选择接单等级'))
    } else {
      callback()
    }
  }
  // 校验是否选择了店铺
  const storeNamePass = (rule, value, callback) => {
    if (!state.store.id) {
      callback(new Error('请选择店铺'))
    } else {
      callback()
    }
  }
  // 添加 编辑 form
  let formRef = ref(null);
  const form = reactive({
    model: {
      actTimerange:[],//活动时间范围

    },
    rules: {
      title: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
      title_cover_image: [{ required: true, message: '请选择任务封面图', trigger: 'blur' }],
      actTimerange: [{ required: true, message: '请选择活动时间', trigger: 'blur' }],
      start_time: [{ required: true, message: '请选择上架时间', trigger: 'blur' }],
      platform_require: [{ required: true, message: '请选择平台要求', trigger: 'blur' }],
      work_form: [{ required: true, message: '请选择作品形式', trigger: 'blur' }],
      province_limit: [{ required: true, message: '请输入地域要求', trigger: 'blur' }],
      levelList: [{ required: true,validator:levelListPass, message: '请选择接单等级', trigger: 'blur' }],
      storeName: [{ required: true,validator:storeNamePass, message: '请选择店铺', trigger: 'blur' }],
    },
  });
  const loading = ref(false);

  // 选择店铺
  function openStoreList(){
    useModal(
      storeList,
      { title: '选择店铺',id:state.store.id},
      {
        confirm: (e) => {
          console.log(e.row.store[0])
          state.store=e.row.store[0]
          form.model.storeName=state.store.name
          form.model.storeTell=state.store.phone
          form.model.storeAddress=state.store.address

          
        },
      },
    );
  }

  

  // 素材列表
  async function getFileGroup(){
    const res = await api.group.list()
    state.groupList=res.data
  }

  const keyArr={level:'团购等级',pernum:'招募人数',cps:'CPS',reward:'报酬',fans:'粉丝'}
  // 等级要求格式化
  function leveltoString(obj){
    let arr=[]
    for(let key in obj){
      if(obj[key]!=null&&key!='txt'){
          arr.push((keyArr[key]?keyArr[key]:'')+obj[key])
      }
      
    }
    return arr.join('-')

  }

  // 编辑等级
  function changeLevel(index){
    useModal(
      editLevel,
      { title: '添加等级要求',type:'edit',data:state.levelList[index] },
      {
        confirm: (e) => {
          state.levelList[index]={...e.data,txt:leveltoString(e.data)}
          console.log(state.levelList[index])

        },
      },
    );
  }
// 添加等级要求
  function addLevel(){
    useModal(
      editLevel,
      { title: '添加等级要求',type:'add' },
      {
        confirm: (e) => {
          console.log(e.data)
          state.levelList.push({...e.data,txt:leveltoString(e.data)})

        },
      },
    );
  }
// 删除
function delLevel(index){
  state.levelList.splice(index,1)
}


  // 获取详情
  async function getDetail(id) {
    loading.value = true;
    const { error, data } = await api.real.detail(id);
    if(error === 0){
      form.model = data
      form.model.work_form=form.model.work_form.split(',')
      form.model.platform_require=form.model.platform_require.split(',')
      form.model.actTimerange=[form.model.activity_time,form.model.end_time]
      state.levelList=form.model.receiving_level
      state.store=form.model.store
      loading.value = false;
    
    }
  }
  // 表单关闭时提交
  async function confirm() {
    // 表单验证
    unref(formRef).validate(async (valid) => {
      if (!valid) return;
      let submitForm = cloneDeep(form.model);
      submitForm={
        ...submitForm,
        activity_time:submitForm.actTimerange[0],
        end_time:submitForm.actTimerange[1],
        store_id:state.store.id,
        platform_require:submitForm.platform_require.join(','),
        work_form:submitForm.work_form.join(','),
        receiving_level:state.levelList
      }
      delete submitForm.id
      const { error } =
        props.modal.params.type == 'add'||props.modal.params.type == 'again'
          ? await api.real.add(submitForm)
          : ''
      if (error == 0) {
        emit('modalCallBack', { event: 'confirm' });
      }
    });
  }


  async function init() {
    if (props.modal.params.id) {
      await getDetail(props.modal.params.id);
    }
    // 素材列表
    await getFileGroup()
  }
  onMounted(() => {
    init();
  });
</script>
<style lang="scss" scoped>
div{
  font-size:13px;
}
.left-t{
  color: red;
  text-align: right;
  flex-shrink: 0;
  word-break:keep-all;
}
.title{
  font-size:18px;
  margin:15px 0 15px 20px;
}
.line{
  line-height: 2em;
  align-items: start;
}

</style>